package monster.com.cvh.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.DialogFragment;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import monster.com.cvh.R;
import monster.com.cvh.bean.ResultBean;
import monster.com.cvh.util.CustomToast;
import monster.com.cvh.util.KeyboardUtils;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.RegexUtils;
import monster.com.cvh.util.SPUtils;
import monster.com.cvh.util.ToastUtils;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @author: 13580
 * @data: 2018/4/8
 * @function:提示信息填写完整DialogFragment
 */
public class SendResumeDialogFragment extends DialogFragment {
    private static final String TAG = "SendResumeDialogFragmen";
    private static final String TEMPLATE_ID = "template_id";
    private View mView;
    private EditText mEdtEmail;
    private TextView mTvSend;
    private int mTemplateId = 1;
    private Context mContext;

    public static SendResumeDialogFragment getInstance(int templateId) {
        Bundle args = new Bundle();
        args.putInt(TEMPLATE_ID, templateId);
        SendResumeDialogFragment fragment = new SendResumeDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            onCurrentAttach(context);
        }
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            onCurrentAttach(activity);
        }
    }

    /**
     * 重写此方法替代onAttacSendResumeDialogFragmenth()高低版本不兼容
     * @param context
     */
    protected void onCurrentAttach(@NonNull Context context){
        mContext=context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            mTemplateId = args.getInt(TEMPLATE_ID);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_resume_email, null);
        return mView;
    }

    @Override
    public void onStart() {
        super.onStart();
        Window win = getDialog().getWindow();
        // 一定要设置Background，如果不设置，window属性设置无效
        win.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.white)));
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams params = win.getAttributes();
        params.gravity = Gravity.BOTTOM;
        // 使用ViewGroup.LayoutParams，以便Dialog 宽度充满整个屏幕
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.dimAmount = 0.3f;
        win.setAttributes(params);

        mEdtEmail = (EditText) mView.findViewById(R.id.edt_dialog_resune_email);
        mEdtEmail.requestFocus();
        mTvSend = (TextView) mView.findViewById(R.id.tv_dialog_resune_email);
        mTvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String email = mEdtEmail.getText().toString();
                if (!email.isEmpty() && RegexUtils.isEmail(email)) {
                    OkGo.<String>get(MyConstant.SEND_RESUME_EMAIL)
                            .tag(this)
                            .params(MyConstant.EMAIL, email)
                            .params(MyConstant.TOKEN, SPUtils.getString(getContext(), MyConstant.TOKEN, ""))
                            .params(MyConstant.TEMPLATE_ID, mTemplateId)
                            .execute(new StringCallback() {
                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    try {
                                        ResultBean bean = new Gson().fromJson(s, ResultBean.class);
                                        if (bean != null) {
                                            int code = bean.getCode();
                                            if (code==1){
                                                showToastShort(R.string.activity_down_and_send_resume_sended_tips);
                                            }else {
                                                showToastShort( bean.getMsg());
                                            }
                                            dismiss();
                                        } else {
                                            showToastShort( bean.getMsg());
                                        }
                                    } catch (JsonSyntaxException e) {
                                        e.printStackTrace();
                                        showToastShort(R.string.net_load_failed);
                                    }
                                }

                                @Override
                                public void onError(Call call, Response response, Exception e) {
                                    super.onError(call, response, e);
                                    showToastShort(R.string.net_load_failed);
                                }
                            });
                } else {
                    showToastShort(R.string.activity_down_and_send_resume_email_error);
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        KeyboardUtils.hideSoftInput((Activity) mContext);
        super.onDestroyView();
    }

    protected void showToastShort(@StringRes int res) {
        ToastUtils.setGravity(Gravity.CENTER, 0, 0);
        CustomToast.show(getResources().getString(res), Toast.LENGTH_SHORT);
    }

    protected void showToastLong(@StringRes int res) {
        ToastUtils.setGravity(Gravity.CENTER, 0, 0);
        CustomToast.show(getResources().getString(res), Toast.LENGTH_LONG);
    }

    protected void showToastShort(String content) {
        ToastUtils.setGravity(Gravity.CENTER, 0, 0);
        CustomToast.show(content, Toast.LENGTH_SHORT);
    }
}

